package com.tjakus.mail;

import javax.mail.*;
import javax.mail.internet.*;
import com.tjakus.hibernate.Users;
import com.tjakus.logging.Logging;
import java.util.*;

/**
 * This class sends mail over gmail account
 * 
 * @deprecated because it is not possible to use in ETK network
 * 
 * @author tjakus
 * 
 */

public class MailOverGmail {

	public void postMail(Users user, String subject, String message)
			throws MessagingException {
		boolean debug = false;

		// If users list fetched from DB is empty skip everything
		if (user != null) {

			// Set the host smtp address - from gmail with authentication
			/*
			 * Properties props = new Properties(); props.put("mail.smtp.auth",
			 * "true"); props.put("mail.smtp.starttls.enable", "true");
			 * props.put("mail.smtp.host", "smtp.gmail.com");
			 * props.put("mail.smtp.port", "567");
			 */
			// Set the host smtp address - from gmail with authentication over SSL
			Properties props = new Properties();
			props.put("mail.smtp.host", "smtp.gmail.com");
			props.put("mail.smtp.socketFactory.port", "465");
			props.put("mail.smtp.socketFactory.class",
					"javax.net.ssl.SSLSocketFactory");
			props.put("mail.smtp.auth", "true");
			props.put("mail.smtp.port", "465");

			// create some properties and get the default Session
			Session session = Session.getInstance(props,
					new javax.mail.Authenticator() {
						protected PasswordAuthentication getPasswordAuthentication() {
							return new PasswordAuthentication("mali.moj.oglas@gmail.com",
									"MaliMojOglas999");
						}
					});

			session.setDebug(debug);

			// create a message
			Message msg = new MimeMessage(session);

			// set the from address
			InternetAddress addressFrom = new InternetAddress("njuskalo@njuskalo.hr");
			msg.setFrom(addressFrom);

			// set BCC address fetched from DB
			/*
			 * InternetAddress[] addressTo = new InternetAddress[users.size()]; int i
			 * = 0; for (Iterator<Users> iter = users.iterator(); iter.hasNext();) {
			 * Users user = iter.next();
			 * Logging.getLogger().debug("Mail - postMail - [ " + user.getEmail() +
			 * " ]"); addressTo[i] = new InternetAddress(user.getEmail()); i++; }
			 * msg.setRecipients(Message.RecipientType.BCC, addressTo);
			 */

			// set TO address
			Logging.getLogger()
					.debug("Mail - postMail - [ " + user.getEmail() + " ]");
			InternetAddress addressTo = new InternetAddress(user.getEmail());
			msg.setRecipient(Message.RecipientType.TO, addressTo);

			// Setting the Subject and Content Type
			msg.setSubject(subject);
			msg.setContent(message, "text/plain");
			Transport.send(msg);
			Logging.getLogger().info(
					"Mail - postMail - e-mail sent [ " + user.getEmail() + " ]");
		} else {
			Logging.getLogger().debug(
					"Mail - postMail - [ e-mail has NOT been sent, no recipients ]");
		}

	}
}
